package com.carlinfo.usercenter.servlet.back;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSONObject;
import com.carlinfo.usercenter.common.servlet.BaseServlet;
import com.carlinfo.usercenter.common.util.DateUtil;
import com.carlinfo.usercenter.common.util.EncryptUtil;
import com.carlinfo.usercenter.common.util.PageInfoUtil;
import com.carlinfo.userscenter.users.pojo.AAdmins;
import com.carlinfo.userscenter.users.pojo.ARole;
import com.carlinfo.userscenter.users.pojo.ARoleEnum;
import com.carlinfo.userscenter.users.service.IUsersService;
import com.carlinfo.userscenter.users.service.impl.UsersServiceImpl;

/**
 * 第二个servlet
 * 只存储和管理员息息相关的信息
 * 登录后的操作 
 * @author jjh
 *
 */
public class AdminsBackServlet extends BaseServlet
{
	/* 用户服务类 */
	private IUsersService usersService = new UsersServiceImpl();
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("===AdminsBackServlet===service===");
		
		String method = request.getParameter("method");
		
		if("main".equalsIgnoreCase(method))
		{
			/* 登录后的首页 */
			main(request,response);
		}else if("welcome".equalsIgnoreCase(method))
		{
			/* 欢迎界面 */
			welcome(request,response);
		}else if("logout".equalsIgnoreCase(method))
		{
			/* 退出 */
			logout(request,response);
		}else if("adminsList".equalsIgnoreCase(method))
		{
			/* 管理员列表 */
			adminsList(request,response);
		}else if("adminsInsert".equalsIgnoreCase(method))
		{
			/* 打开管理员添加页面 */
			adminsInsert(request,response);
		}else if("adminsInsertSubmit".equalsIgnoreCase(method))
		{
			/* 管理员添加提交操作 */
			adminsInsetSubmit(request,response);
		}else if("adminsUpdate".equalsIgnoreCase(method))
		{
			/* 打开管理员更新页面 */
			adminsUpdate(request,response);
		}else if("adminsUpdateSubmit".equalsIgnoreCase(method))
		{
			/* 管理员更新提交操作 */
			adminsUpdateSubmit(request,response);
		}
	}
	
	/**
	 * 管理员更新提交 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void adminsUpdateSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		
		System.out.println("===adminsUpdateSubmit==");
		/* 接收参数 */
		String roleId = request.getParameter("roleId");
		String email = request.getParameter("email");
		String trueName = request.getParameter("trueName");
		String sex = request.getParameter("sex");
		String phone = request.getParameter("phone");
		String qq= request.getParameter("qq");
		String status = request.getParameter("status");
		
		/* 处理参数
		 * 由于request.getParameter返回值全部是String
		 * 而POJO的参数类型不一定是String,
		 * 需要处理
		 *  */
		/* 将字符串转换成Byte */
		byte sexByte = Byte.valueOf(sex);
		int roleIdInt = Integer.valueOf(roleId);
		byte statusByte = Byte.valueOf(status);
		
		/*需要根据id到数据库里面找一遍
		 * 接收参数
		 * 在更新的时候多接收了一个id(一定一定要在表单提交的时候加上此id)
		 */
		String id = request.getParameter("id");
		/* 根据id查询管理员 */
		Map<String,Object> condMap = new HashMap<String,Object>();
		/*往map中放条件
		 * 键:在dao使用的时候指定
		 * 值:是条件的值
		 */
		condMap.clear();
		condMap.put("id",id);
		condMap.put("extend", "true");
		AAdmins admins = this.usersService.findOneAdminsService(condMap);
		/* 为对象赋值
		 * 用户自己填写,从页面中获取 */
		admins.setRoleId(roleIdInt);
		admins.setEmail(email);
		admins.setTrueName(trueName);
		admins.setSex(sexByte);
		admins.setPhone(phone);
		admins.setQq(qq);
		admins.setStatus(statusByte);
		/* 系统生成 */
		admins.setUpdateTime(new Date());
		/* 调用service方法 */
		JSONObject resultDbJSON = this.usersService.updateOneAdminsService(admins);
		/* 将Service方法的结果存储于四大作用域中 */
		String info = resultDbJSON.getString("info");
		request.setAttribute("info", info);
		/* 保留出错信息,请把辛辛苦苦拼装的管理员对象也存储 */
		request.setAttribute("admins", admins);
		/* 默认是服务器端跳转是一个页面 */
		/*this.adminsInsert(request, response);*/
		/* 原生的回信办法 
		 * 再也不用跳转了
		 * 这种情况只能适用于JSON
		 * */
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		/* 输出字符流 */
		out.println(resultDbJSON.toJSONString());
		/* 控管子 */
		out.flush();
		/* 关闭管子 */
		out.close();
	}
	
	/**
	 * 打开管理员更新页面 
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void adminsUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String path = "/WEB-INF/jsp/back/admins/adminsInfo.jsp" ;
		/* 接收参数 */
		String id = request.getParameter("id");
		/* 根据id来查询管理员 */
		Map<String,Object> condMap = new HashMap<String,Object>();
		/* 往map中放条件
		 * 键:在dao使用的时候指定
		 * 值:是条件的值
		 *  */
		condMap.clear();
		condMap.put("id", id);
		condMap.put("extend", "true");
		AAdmins admins = this.usersService.findOneAdminsService(condMap);
		request.setAttribute("admins",admins);
		
		/* 角色只有在更新的时候才能使用查看不需要查询所有角色 */
		String operType = request.getParameter("operType");
		if("adminsUpdate".equalsIgnoreCase(operType))
		{
			path = "/WEB-INF/jsp/back/admins/adminsUpdate.jsp" ;
			/*
			 * 查询所有的角色,不能分页
			 * 只查询启用的角色
			 */
			condMap.clear();
			condMap.put("status",ARoleEnum.STATUS_ENABLE.getStatus());
			List<ARole> roleList = this.usersService.findCountListRoleService(null, condMap);
			/* 将结果放到四大作用域中 */
			request.setAttribute("roleList", roleList);
		}
		
		
		/* 服务器端跳转 */
		request.getRequestDispatcher(path).forward(request, response);
		
		 
	}

	/**
	 * 管理员添加提交页面
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void adminsInsetSubmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("==adminsInsetSubmit==");
		Map<String,Object> condMap = new HashMap<String,Object>();
		
		/* 所有的request请求只要是二进制流的方式提交,必须用common-filedupload来解析 */
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);
		
		/* 接收参数 */
		String roleId = request.getParameter("roleId");
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String trueName = request.getParameter("trueName");
		String sex = request.getParameter("sex");
		String phone = request.getParameter("phone");
		String qq = request.getParameter("qq");
		String status = request.getParameter("status");
		
		try
		{
			/* 解析控件 */
			List<FileItem> fileItemList = sfu.parseRequest(request);
			for (Iterator iterator = fileItemList.iterator(); iterator.hasNext();)
			{
				FileItem fileItem = (FileItem) iterator.next();
				/* 因为是二进制提交,所以接收参数的时候需要单独处理一下 */
				/*
				 * fileItem.getFiledName():表单中name的值
				 * fileItem.getName():上传文件的名字 
				 */
				//System.out.println(fileItem.getFieldName() + "===" + fileItem.getName());
				/* 判断此字段是否是二进制字段还是文本字段 */
				if(fileItem.isFormField())
				{
					/* 获取控件的值 */
					String value = fileItem.getString();
					if("roleId".equalsIgnoreCase(fileItem.getFieldName()))
					{
						roleId = value ;
					}else if("email".equalsIgnoreCase(fileItem.getFieldName()))
					{
						email = value ;
					}else if("password".equalsIgnoreCase(fileItem.getFieldName()))
					{
						password = value ;
					}else if("trueName".equalsIgnoreCase(fileItem.getFieldName()))
					{
						trueName = value ;
					}else if("sex".equalsIgnoreCase(fileItem.getFieldName()))
					{
						sex = value ;
					}else if("phone".equalsIgnoreCase(fileItem.getFieldName()))
					{
						phone = value ;
					}else if("qq".equalsIgnoreCase(fileItem.getFieldName()))
					{
						qq = value ;
					}else if("status".equalsIgnoreCase(fileItem.getFieldName()))
					{
						status = value ;
					}
				}else
				{
					/*
					 * 不是表单字段,二进制字段 
					 * jgg
					 */
					String fileName = fileItem.getName() ;
					InputStream is = fileItem.getInputStream();
					/**
					 * 如何处理二进制图片呢
					 * 放到service来做
					 */
					condMap.put("fileName", fileName);
					condMap.put("is", is);
				}
			}
		} catch (FileUploadException e)
		{
			e.printStackTrace();
		}
		/*
		 * 处理参数
		 * 由于是request.getParameter返回值全部是String
		 * 而pojo的参数不一定是String
		 * 需要处理
		 */
		/* 将字符串转换成Byte */
		byte sexByte = Byte.valueOf(sex);
		int roleIdInt = Integer.valueOf(roleId);
		byte statusByte = Byte.valueOf(status);
		
		/* new一个对象 */
		AAdmins admins = new AAdmins() ;
		/* 为对象赋值 */
		/* 用户自己填写;从页面获取 */
		admins.setRoleId(roleIdInt);
		admins.setEmail(email);
		/* 采用高级的加密算法(随机盐) */
		admins.setPassword(this.encryptUtil.encodeStr(password));
		admins.setTrueName(trueName);
		admins.setSex(sexByte);
		admins.setPhone(phone);
		admins.setQq(qq);
		admins.setStatus(statusByte);
		/* 系统生成 */
		admins.setCreateTime(new Date());
		admins.setUpdateTime(new Date());
		admins.setLastloginTime(new Date());
		admins.setPubTime(new Date());
		
		/* 调用service方法 */
		JSONObject resultDbJSON = this.usersService.saveOneAdminsService(admins,condMap);
		/* 将service方法的结果存储到四大作用域 */
		String info = resultDbJSON.getString("info");
		request.setAttribute("info", info);
		/* 保存出错信息,请把辛辛苦苦拼装的管理员对象也存储 */
		request.setAttribute("admins", admins);
		/*
		 * 默认是服务器跳转到一个页面
		 */
//		this.adminsInsert(request, response);
		/*
		 * 原生的回信办法
		 * 再也不用跳转了
		 * 这种情况只能适用于JSON
		 */
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		/* 输出字符流 */
		out.println(resultDbJSON.toJSONString());
		/* 控管子 */
		out.flush();
		/* 关闭管子 */
		out.close();
	}
		
	/**
	 * 	管理员添加界面
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void adminsInsert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		Map<String,Object> condMap = new HashMap<String,Object>();
		/*
		 * 查询所有的角色,不能分页
		 * 只查询启用的角色
		 */
		condMap.put("status", ARoleEnum.STATUS_ENABLE.getStatus());
		List<ARole> roleList = this.usersService.findCountListRoleService(null, condMap);
		/* 将结果放到四大作用域中 */
		request.setAttribute("roleList", roleList);
		/* 跳转的路径 */
		String path = "/WEB-INF/jsp/back/admins/adminsInsert.jsp" ;
		/* 服务端跳转 */
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 管理员列表
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void adminsList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		PageInfoUtil pageInfoUtil = this.proccedPageInfoUtil(request);
		/*
		 * 所有的条件要想变活
		 * 需要从页面上接收
		 * 返回值是字符串
		 * 
		 * 如果页面没有传,返回值是null
		 * 
		 * 接收参数
		 */
		String keyword = request.getParameter("keyword");
		String status = request.getParameter("status");
		/*
		 * st:开始时间
		 * ed:结束时间
		 */
		String st = request.getParameter("st");
		String ed = request.getParameter("ed");
		
		/* 所有的数据我都处理一下
		 * 不管是null,还是""都变成空字符串
		 * 
		 * 处理参数
		 */
		if(keyword == null)
		{
			keyword = "" ;
		}
		if(status == null)
		{
			status = "" ;
		}
		if(st == null)
		{
			st = "" ;
		}
		if(ed == null)
		{
			ed = "" ;
		}
		
		Date stDate = null ;
		Date edDate = null ;
		
		/*
		 * st要么是空字符串,要么有值
		 */
		if(!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			/* 将字符串变成日期 */
			stDate = dateUtil.strToDateTime(st);
			edDate = dateUtil.strToDateTime(ed);
		}
		/* 搜索的条件
		 * 搜索的条件不等于SQL语句的条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		
		condMap.put("keyword", keyword);
		condMap.put("status", status);
		condMap.put("stTime", stDate);
		condMap.put("edTime", edDate);
		/* 排序 */
		condMap.put("orderby", "idasc");
		condMap.put("extend", "true");
		System.out.println("==查询条件==" + condMap);
		List<AAdmins> adminsList = this.usersService.findCountListAdminsService(pageInfoUtil,condMap);
		
		/* 将结果存储到四大作用域中,是为了在页面上显示 */
		request.setAttribute("adminsList", adminsList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);
		
		/*
		 * 保存搜索条件 
		 */
		request.setAttribute("keyword", keyword);
		request.setAttribute("status", status);
		request.setAttribute("st", st);
		request.setAttribute("ed", ed);
		
		String path = "/WEB-INF/jsp/back/admins/adminsList.jsp" ;
		/*
		 * 服务端跳转到jsp
		 * 因为要写HTML版本的回信
		 */
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 退出
	 * 登录做了什么,退出也得做啥?(退票)
	 * @throws IOException 
	 */
	private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		HttpSession session = request.getSession();
		/* 退票 */
		session.removeAttribute("adminsSess");
		/*销毁整个session
		 * 退出浏览器了
		 */
		String info = "退出成功,请放心" ;
		session.setAttribute("info", info);
		/* 退出使用客户端跳转 */
		response.sendRedirect(request.getContextPath() + "/NoLoginBackServlet?method=login");
	}

	/**
	 * 欢迎界面
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void welcome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String path = "/WEB-INF/jsp/back/admins/welcome.jsp" ;
		/* 服务器跳转 */
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 登录后的首页 
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String path = "/WEB-INF/jsp/back/admins/main.jsp" ;
		/* 服务器跳转 */
		request.getRequestDispatcher(path).forward(request, response);
	}
}
